package mystack;

import javax.jws.Oneway;
import java.util.Deque;
import java.util.LinkedList;

/**
 * 224 基本计算器
 *  输入 s="(1+(4+5+2)-3+(6+8))"
 *  输出 23
 *  双栈思路
 */
public class DoubleStackCalc {

    public int calc(String context){
        Deque<Character> ops=new LinkedList();
        Deque<Integer> nums=new LinkedList();
        nums.push(0);
        context = context.replaceAll(" ", "");
        int length = context.length();
        char[] chars = context.toCharArray();
        for (int i = 0; i <length ; i++) {
            char c = chars[i];
            if(c=='('){
                ops.push(c);
            }else if(c==')'){
                //计算
                while (!ops.isEmpty()){
                    Character peek = ops.peek();
                    if(peek!='('){
                        guibin(ops,nums);
                    }else{
                        ops.pop();
                    }
                }
            }else if(isNum(c)){
                int n=0;
                int ret=0;
                while (i<length&&isNum(chars[i])){
                    ret=n*10+chars[i]-'0';
                    i++;
                }
                i--;
                nums.push(ret);
                while (!ops.isEmpty()&&nums.size()>1&&ops.peek()!='('){

                        guibin(ops,nums);
                }
            }else{
                ops.push(c);

            }
        }
        return nums.peek();
    }

    public void  guibin(Deque<Character> ops, Deque<Integer> nums){
        int re=0;
           Integer one = nums.pop();
           Integer two = nums.pop();
       if(ops.pop()=='+'){
           re=one+two;
       }else{
           re=two-one;
       }
       nums.push(re);
    }
    private boolean isNum(char c){
        return Character.isDigit(c);
    }

    public static void main(String[] args) {
        DoubleStackCalc doubleStackCalc = new DoubleStackCalc();
        int calc = doubleStackCalc.calc("+1+(4+5+2)-3+(6+8)");
        System.out.println(calc);
    }
}
